package cn.jorian.framework.service.impl;

import cn.jorian.framework.bean.ApiRequestParam;
import cn.jorian.framework.bean.GoodsBean;
import cn.jorian.framework.bean.ResponseResult;
import cn.jorian.framework.config.AppConfig;
import cn.jorian.framework.service.ICheckService;
import cn.jorian.framework.util.Base64Util;
import cn.jorian.framework.util.GsonUtil;
import cn.jorian.framework.util.MD5Util;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;

/**
 * 校验数据合法性
 */
@Service
public class CheckServiceImpl implements ICheckService {

    @Override
    public ResponseResult checkLegal(ApiRequestParam bean) {

        //appkey配置
        AppConfig appConfig = getAppconfig();
        //请求参数
        String appkey = bean.getAppkey();
        if (appkey.isEmpty() || !appkey.equals(appConfig.getAppKey())) {
            return ResponseResult.fail("appkey 错误");
        }
        //时间戳
        String timestamp = bean.getTimestamp();
        if (timestamp.isEmpty() || timestamp.length() != 14) {
            return ResponseResult.fail("timestamp 错误");
        }
        String data = bean.getData();
        if (data.isEmpty()) {
            return ResponseResult.fail("data 错误");
        }

        //签名
        String sign = bean.getSign();

        //md5
        String md5 = MD5Util.md5Hex(bean.getTimestamp() + bean.getData() + appConfig.getAppPassword());
        if (sign.isEmpty() || !sign.equals(md5)) {
            return ResponseResult.fail("sign 错误");
        }

        String decodeData = Base64Util.decode(data);
        System.out.println("decodeData:" + decodeData);
//        result.setData();
        return ResponseResult.success();
    }

    @Override
    public AppConfig getAppconfig() {
        AppConfig appConfig = new AppConfig("9476d5ce-fc6c-4ed6-a7fb-9a9d63f2d9f4", "zmCoObWLQ6rH1nnGeh92F3et3RbvTAt1");
        return appConfig;
    }
}
